package com.neuedu.mvc.controller;

import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/***
 *  http://127.0.0.1:8080/mvc/human
 */
@WebServlet(name = "HumanController", value = "/human")
public class HumanController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //像客户端输出一个 JSON数组

        List list = new ArrayList();

        for (int i = 1; i <= 10; i++) {
            Map human = new HashMap();

            /**
             * date: '2016-05-02',
             * 					name: '王小虎',
             * 					address: '上海市普陀区金沙江路 1518 弄'
             */
            human.put("id" ,i);
            human.put("date" ,"2022-11-09 15:43:"+i);
            human.put("name" ,"王小虎"+i);
            human.put("address" ,"上海市普陀区金沙江路 "+i+"号");


            list.add(human);
        }

        
        //允许前端跨域访问
        // response.addHeader("Access-Control-Allow-Origin","*");

        
        
        //list -->  String(JSON)    vuejs拿到string 转换成JS 认识的JSON对象
        String json = JSON.toJSONString(list);


        //设置ContentType
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        out.write(json);
        out.flush();
        out.close();

    }
}
